package com.seadragon.app.ksr.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.seadragon.app.ksr.dao.EventScheduleDao;
import com.seadragon.app.ksr.model.Address;
import com.seadragon.app.ksr.model.Event;
import com.seadragon.app.ksr.model.EventSchedule;
import com.seadragon.app.ksr.service.AddressService;
import com.seadragon.app.ksr.service.EventScheduleService;
import com.seadragon.app.ksr.util.IndexManager;

@Service("eventScheduleService")
@Transactional
public class EventScheduleServiceImpl implements EventScheduleService {
	private Logger logger = LoggerFactory.getLogger(EventScheduleServiceImpl.class);
	@Autowired
	private EventScheduleDao eventScheduleDao;

	@Autowired
	private AddressService addressService;

	@Autowired
	private IndexManager indexManager;
	
	@Override
	public EventSchedule update(EventSchedule eventSchedule) {
		List<Address> addresses = eventSchedule.getEventAddresses();
		for(int i = 0; i < addresses.size(); i++){
			Address address2 = addressService.save(addresses.get(i));
			addresses.set(i, address2);
		}
		try {
			indexManager.insertDocument(eventSchedule.getEvent());
			eventScheduleDao.update(eventSchedule);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		return null;
	}
	
	@Override
	public void save(EventSchedule eventSchedule) {
		List<Address> addresses = eventSchedule.getEventAddresses();
		for(int i = 0; i < addresses.size(); i++){
			Address address2 = addressService.save(addresses.get(i));
			addresses.set(i, address2);
		}
		try {
			indexManager.insertDocument(eventSchedule.getEvent());
			eventScheduleDao.save(eventSchedule);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	@Override
	public List<EventSchedule> findAllEventSchedulesBy(Event event) {
		return eventScheduleDao.findAllBy(event);
	}
}
